<?php
class Custom_Model_Filemanager {
	public function resize($filename, $width, $height) {
		if (!file_exists(UPLOAD_PATH .'/'. $filename) || !is_file(UPLOAD_PATH .'/' . $filename)) {
			return;
		} 
		
		$info = pathinfo($filename);
		$extension = $info['extension'];
		
		$old_image = $filename;
		$new_image = 'cache' . substr($filename, 0, strrpos($filename, '.')) . '-' . $width . 'x' . $height . '.' . $extension;
		
		if (!file_exists(UPLOAD_PATH .'/' . $new_image) || (filemtime(UPLOAD_PATH .'/' . $old_image) > filemtime(UPLOAD_PATH .'/' . $new_image))) {
			$path = '';
			
			$directories = explode('/', dirname(str_replace('../', '', $new_image)));
			
			foreach ($directories as $directory) {
				$path = $path . '/' . $directory;
				
				if (!file_exists(UPLOAD_PATH .'/' . $path)) {
					@mkdir(UPLOAD_PATH .'/' . $path, 0777);
				}		
			}
			
			$image = new Custom_Image(UPLOAD_PATH .'/' . $old_image);
			$image->resize($width, $height);
			$image->save(UPLOAD_PATH .'/' . $new_image);
		}
	
		return 'public/uploads/'.$new_image;
	}
}
?>